package ar.edu.unicen.pladema.ui.mywidgets;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;

import ar.edu.unicen.pladema.main.SWTUtils;
import ar.edu.unicen.pladema.resources.ResourceManager;
import ar.edu.unicen.pladema.ui.model.ColorRange;
import ar.edu.unicen.pladema.ui.panel.AbstractPanel;

public class ColorList extends AbstractPanel {
	private Group group;
	private Button agregar;
	private int max = Integer.MAX_VALUE;

	public ColorList(Composite parent) {
		super(parent);
	}

	@Override
	protected void createWidgets() {
		group = new Group(this, SWT.SHADOW_ETCHED_IN);
		group.setText(ResourceManager.getInstance().getText("COLORLIST_TITLE"));
		agregar = SWTUtils.createButton(this, "ADD", new Listener() {
			@Override
			public void handleEvent(Event arg0) {
				addItem();
			}
		});
	}
	public void addItem() {
		ColorRange newRange = this.getColorRange();
		while (group.getChildren().length > 0) {
			group.getChildren()[0].dispose();
		}
		newRange.add(max, new RGB(0,0,0));
		setColorRange(newRange);
		this.pack();
		this.getParent().layout();
	}
	@Override
	protected void layoutWidgets() {
		this.setLayout(new FormLayout());
		group.setLayout(new FillLayout(SWT.VERTICAL));
		group.setLayoutData(SWTUtils.createTopFormData());
		agregar.setLayoutData(SWTUtils.createBelowFormData(group));
	}

	/**
	 * @return the colorRange
	 */
	public ColorRange getColorRange() {
		ColorRange result=null;
		for (int i=0; i<group.getChildren().length; i++) {
			Control control = group.getChildren()[i];
			if (control instanceof ColorListItem) {
				ColorListItem colorListItem = (ColorListItem) control;
				int index = Integer.parseInt(colorListItem.getText());
				if (result == null) {
					result = new ColorRange(index, colorListItem.getColor());
				} else {
					result.add(index, colorListItem.getColor());
				}
			}
		}
		return result;
	}

	/**
	 * @param colorRange the colorRange to set
	 */
	public void setColorRange(ColorRange colorRange) {
		int i = 0;
		while (group.getChildren().length > i) {
			Control control = group.getChildren()[0];
			if (control instanceof ColorListItem) {
				group.getChildren()[0].dispose();
			} else {
				i++;
			}
		}
		//this.getChildren()[0].dispose();
		ColorRange cr = colorRange;
		while(cr != null) {
			ColorListItem cli = new ColorListItem(group, this);
			cli.setText(Integer.toString(cr.getIndex()));
			cli.setColor(cr.getColor());
			cr = cr.getNext();
		}
		this.pack();
		this.getParent().layout();
	}

	public void sort() {
		ColorRange newRange = this.getColorRange();
		setColorRange(newRange);
		this.pack();
		this.getParent().layout();
	}

}
